<template>
  <div ref="wrapper" :style="{ height:  '100%'}" class="all-orders">
    <v-loadmore :top-method="loadTop" :topDistance="20" :maxDistance="140" :auto-fill="false" ref="loadmore" @top-status-change="handleTopChange" style="height:100%">
      <ul class="form-style-top" v-infinite-scroll="loadMore" infinite-scroll-disabled="loading" infinite-scroll-distance="30">
        <div v-for="(item,index) in list" :key="index" class="form-style-box">
          <div @click="toJumpOrderDetails(item.orderId,item.orderType,item)">
            <li class="order-time">
              <span v-html="CommonUtil.timestampToTime(item.createTime)"></span>
              <div class="color-red" v-if="item.status==1">待付款</div>
              <div class="color-yellow" v-if="item.status==2">待处理</div>
              <div class="buy-num" v-if="item.status==3">已完成</div>
            </li>
            <!-- <li class="order-list" v-for="(itemBar,index) in item" :key="index" @click="jumptoOrderDetails"> -->
            <!-- 聚客宝产品直接显示总价(其他产品显示单价)，数量为1(其他产品显示buyNum字段) -->
            <li class="order-list" v-for="(machineItem,index) in item.machineLists" :key="index">
              <div class="context-left">
                <img class="mainImg" :src="devicePic(machineItem.machineType)" alt="" />
              </div>
              <div class="context-right">
                <div>
                  <span class="text-left">{{machineItem.machineName}}</span>
                  <span class="text-right" v-if="jkbTypes.includes(machineItem.machineType)">￥ {{item.totalAmount}}</span>
                  <span class="text-right" v-else>￥ {{machineItem.price}}</span>
                </div>
                <div>
                  <span class="text-left"></span>
                  <span class="text-right" v-if="jkbTypes.includes(machineItem.machineType)">x1</span>
                  <span class="text-right" v-else>x{{machineItem.buyNum}}</span>
                </div>
              </div>
            </li>
          </div>
          <li>
            <div class="total-right">
              <p v-if="item.status==1">共{{item.totalNum}}件商品 应付金额：
                <span>￥{{item.totalAmount}}</span>
              </p>
              <p v-if="item.status==2||item.status==3">共{{item.totalNum}}件商品 实付金额：
                <span>￥{{item.realAmount}}</span>
              </p>
              <span class="now-pay" v-if="item.status==1" @click="toPay(item.orderId,item.orderType,item)">立即支付</span>
              <router-link :to="{path:`/mallList/orderRecord/returnDeposit`,query:{orderId:item.orderId,orderWay: item.orderWay}}"  v-if="item.orderWay==1">
                <span class="check-logistics">变更订购方式</span>
              </router-link>
              <router-link :to="{path:`/mallList/orderRecord/viewLogistics`,query:{orderId:item.orderId}}" v-if="item.status==2||item.status==3&&item.orderType&&!orderTypes.includes(item.orderType)">
                <span class="check-logistics" >查看物流</span>
              </router-link>
            </div>
          </li>
          <li>
            <!-- <div v-clipboard:copy="trackingNumber" v-clipboard:success="onCopy" v-clipboard:error="onError">点击复制</div> -->
          </li>
        </div>
      </ul>
      <p v-show="loading" class="page-infinite-loading">
        <mt-spinner :style="{display:'inline-block'}" type="fading-circle"></mt-spinner>
      </p>
      <div v-show="noMore&&!hasError" class="no-more">已经全部加载完毕</div>
      <noData msg="暂无数据" v-if="hasError" />
    </v-loadmore>
  </div>
</template>

<script>
import Vue from "vue";
import jsBridge from "../../../tools/jsBridge.js";
import noData from "../../../components/noData/noData";
import config from "../../../base/profile/config.json";
import { MessageBox, Loadmore, Toast } from "mint-ui";
import VueClipboard from "vue-clipboard2";
Vue.use(VueClipboard);

export default {
  name: "orderRecord",
  data() {
    return {
      CommonUtil: CommonUtil,
      // logisticsCompany: "顺丰快递", //物流公司
      // trackingNumber: "5555555555555555555", //快递单号
      currentPage: 1,
      pageSize: 10,
      noMore: false,
      loading: false,
      list: [],
      hasError: false,
      topStatus: "", //下拉刷新状态
      orderId: "",
      refuseClick: false,
      deviceInfo: [],
      jkbTypes: [34, 35], //聚客宝产品集合
      orderTypes: [5, 6, 7, 8, 9] // 不需要显示物流信息的订单类型
    };
  },
  props: ["selected"],
  methods: {
    handleTopChange(status) {
      this.topStatus = status;
    },
    resetList() {
      this.currentPage = 1;
      this.list = [];
      this.noMore = false;
    },
    loadTop() {
      this.resetList();
      this.loadMore();
    },
    //查看物流
    // viewLogistics() {
    //   MessageBox({
    //     title: "查看物流",
    //     message: "物流公司：" + this.logisticsCompany + "<br/>快递单号：" + this.trackingNumber,
    //     showCancelButton: true,
    //     confirmButtonText: "复制单号"
    //   }).then(action => {
    //     if (action === "confirm") {
    //       //复制单号
    //       this.$copyText(this.trackingNumber).then(function(e) {}, function(e) {});
    //     }
    //   });
    // },
    // jumptoViewLogistics() {
    //   this.$router.push({ path: "/mallList/orderRecord/viewLogistics", query: {} });
    // },
    devicePic(machineType) {
      let img = "./static/images/machines/defaultMachine.png";
      for (const e of this.deviceInfo) {
        if (e.machineType == machineType&&e.thumbnail){
          img = config.shopImgUrlPrefix + e.thumbnail;
          break;
        }
      }
     
      return img;
      //return require(`../../../../static/images/machines/${window.CommonUtil.devicePic(machineType)}`);
    },
    // 跳转商品详情页
    toJumpOrderDetails(orderId,orderType,item) {
      //防止下拉刷新时候触发跳转
      if (this.topStatus == "drop" || this.topStatus == "loading") {
        return;
      } else {
        let machineType=item.machineLists&&item.machineLists.length>0?item.machineLists[0].machineType:"";
        this.$router.push({ path: "/mallList/orderRecord/orderDetails", query: { orderId: orderId,orderType:orderType,machineType:machineType} });
      }
    },
    //获取订购数据
    orderRecordData() {
      this.loading = true;
      let selectedStatus = "";
      if (this.selected == 1) {
        selectedStatus = "";
      } else if (this.selected == 2) {
        selectedStatus = 1;
      } else if (this.selected == 3) {
        selectedStatus = 2;
      } else if (this.selected == 4) {
        selectedStatus = 3;
      }
      this.ajax({
        url: `app/orderService/serviceOrderLists.do?currentPage=${this.currentPage}&pageSize=${this.pageSize}&status=${selectedStatus}`,
        type: "get",
        controlLoading: false
      })
        .then(res => {
          this.loading = false;
          if (res.success) {
            let data = res.resultObject;
            if (data.list) {
              this.list = this.list.concat(data.list);
            }
            if (data.dataCount) {
              this.noMore = Math.ceil(data.dataCount / this.pageSize) === this.currentPage ? true : false;
            } else {
              this.noMore = true;
            }

            this.currentPage++;
            if (this.list.length == 0) {
              this.hasError = true;
            } else {
              this.hasError = false;
            }
          } else {
            this.noMore = true;
            if (res.code > 0 && res.msg) {
              Toast(res.msg);
            } else {
              Toast("服务错误");
            }
          }
          if (this.list.length == 0) {
            this.hasError = true;
          } else {
            this.hasError = false;
          }
          this.$refs.loadmore && this.$refs.loadmore.onTopLoaded && this.$refs.loadmore.onTopLoaded();
        })
        .catch(err => {
          this.loading = false;
          this.noMore = true;
          if (this.list.length == 0) {
            this.hasError = true;
          } else {
            this.hasError = false;
          }
          this.$refs.loadmore && this.$refs.loadmore.onTopLoaded && this.$refs.loadmore.onTopLoaded();
        });
    },
    encodePayInfo(string) {
      let str = string;
      let temp = str.split("&");
      let resultArray = [];
      for (let index = 0; index < temp.length; index++) {
        let item;
        if (temp[index].startsWith("sign=")) {
          item = [];
          item.push("sign");
          item.push(encodeURIComponent(temp[index].slice(5)));
        } else {
          item = temp[index].split("=");
          item[1] = encodeURIComponent(item[1]);
        }
        resultArray.push(item.join("="));
      }
      return resultArray.join("&");
    },
    // 待付款，去支付接口
    toPay(orderId,orderType,item) {
      let machineType=item.machineLists&&item.machineLists.length>0?item.machineLists[0].machineType:"";
      if (this.refuseClick) {
        return;
      }
      this.refuseClick = true;
      
      let successMsg = "";//订购成功页的提示信息
      //联系人信息校验(推广套餐、码卡龙定制广告图、本地生活视频拍摄)
      if (CommonUtil.needLinkInfo(machineType)) {
        successMsg = "我们的业务人员会在2个工作日内与您联系，请保持手机畅通";
      }
      this.ajax({
        url: `app/orderService/toPayOrder.do?orderId=${orderId}`,
        type: "get",
        controlLoading: true
      })
        .then(res => {
          if (res.success && res.resultObject) {
            this.orderId = res.resultObject.orderId;
            jsBridge.tradePay(
              {
                payType: "alipay",
                orderInfo: this.encodePayInfo(res.resultObject.orderInfo)
              },
              result => {
                if (result.resultObject.resultStatus == "9000") {
                  // this.forPayment();
                  this.refuseClick = false;
                  this.$router.push({ path: "/mallList/productDetails/payResult", query: { type: "true", toRouterNum: 1, toRouterRecordNum: 2 , msg: successMsg,machineType:machineType} });
                } else if (result.resultObject.resultStatus == "4000") {
                  // Toast(result.msg);
                  this.refuseClick = false;
                  this.$router.push({ path: "/mallList/productDetails/payResult", query: { type: "false", toRouterNum: 1, toRouterRecordNum: 2 } });
                } else {
                  this.refuseClick = false;
                  this.$router.push({ path: "/mallList/orderRecord/orderDetails", query: { orderId: this.orderId,orderType:orderType,machineType:machineType } });
                }
              }
            );
          } else {
            this.refuseClick = false;
            Toast(res.msg);
          }
        })
        .catch(err => {
          this.refuseClick = false;
          Toast(err.msg);
        });
    },
    //无限加载
    loadMore() {
      if (this.loading || this.noMore) {
        return;
      }
      this.orderRecordData();
    }
  },
  created() {
    CommonUtil.getDeviceInfo().then(data => {
        this.deviceInfo = data;
    });
  },
  components: {
    noData,
    "v-loadmore": Loadmore
  }
};
</script>
<style lang='scss' scoped>
@import "../mall";
</style>
